package linkedlist.leetcode_160;

/**
 * 无环相交链表的起始节点
 *
 */
public class RemoveLengthSolution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null){
            return null;
        }
        //统计两个链表的长度
        int lenA = getLength(headA);
        int lenB = getLength(headB);
        while(lenA != lenB){
            if(lenA > lenB){
                headA = headA.next;
                lenA--;
            }else{
                headB = headB.next;
                lenB--;
            }
        }
        while(headA != headB){
            headA = headA.next;
            headB = headB.next;
        }
        //不相交最终就返回null
        return headA;
    }
    public int getLength(ListNode head){
        int length = 0;
        while (head != null){
            head = head.next;
            length++;
        }
        return length;
    }
}
